/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.topic.service;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.topic.entity.Topic;
import com.jeeplus.modules.topic.mapper.TopicMapper;
import com.jeeplus.modules.topic.entity.TopicTicket;
import com.jeeplus.modules.topic.mapper.TopicTicketMapper;

/**
 * 主题Service
 * @author zhych
 * @version 2021-08-23
 */
@Service
@Transactional(readOnly = true)
public class TopicService extends CrudService<TopicMapper, Topic> {

	@Autowired
	private TopicTicketMapper topicTicketMapper;

	public Topic get(String id) {
		Topic topic = super.get(id);
		if (!Objects.isNull(topic)) {
			topic.setTopicTicketList(topicTicketMapper.findList(new TopicTicket(topic)));
		}
		return topic;
	}

	public List<Topic> findList(Topic topic) {
		return super.findList(topic);
	}

	public Page<Topic> findPage(Page<Topic> page, Topic topic) {
		return super.findPage(page, topic);
	}

	@Transactional(readOnly = false)
	public void save(Topic topic) {
		super.save(topic);
		for (TopicTicket topicTicket : topic.getTopicTicketList()){
			if (topicTicket.getId() == null){
				continue;
			}
			if (TopicTicket.DEL_FLAG_NORMAL.equals(topicTicket.getDelFlag())){
				if (StringUtils.isBlank(topicTicket.getId())){
					topicTicket.setTopic(topic);
					topicTicket.preInsert();
					topicTicketMapper.insert(topicTicket);
				}else{
					topicTicket.preUpdate();
					topicTicketMapper.update(topicTicket);
				}
			}else{
				topicTicketMapper.delete(topicTicket);
			}
		}
	}

	@Transactional(readOnly = false)
	public void delete(Topic topic) {
		super.delete(topic);
		topicTicketMapper.delete(new TopicTicket(topic));
	}

}